package com.mdlib.helper.ui.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.hn.plt.config.ClientConfig;
import com.ljlib.core.util.EmptyUtils;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.common.MDConstant;
import com.mdlib.helper.event.AddServiceEvent;
import com.mdlib.helper.event.PayEvent;
import com.mdlib.helper.event.PayModelEvent;
import com.mdlib.helper.model.entity.RechargeEntity;
import com.mdlib.helper.model.entity.ServiceMoney;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.utils.PayResult;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

import static com.mdlib.helper.ui.UIHelper.ALIPAY;
import static com.mdlib.helper.ui.UIHelper.BALANCE;
import static com.mdlib.helper.ui.UIHelper.BUS_ID;
import static com.mdlib.helper.ui.UIHelper.WECHAT;

/**
 * 作者：HQY on 16/11/23 17:04
 * 邮箱：hqy_xz@126.com
 */

public class OrderDetailsAddMoneyDialog extends DialogFragment {
    private static final String SERVICEMONEY = "servicemoney";

    @Bind(R.id.iv_service_money_subtract)
    ImageView mIvServiceMoneySubtract;
    @Bind(R.id.et_service_money_number)
    EditText mEtServiceMoneyNumber;
    @Bind(R.id.iv_service_money_add)
    ImageView mIvServiceMoneyAdd;
    @Bind(R.id.tv_service_money_number)
    TextView mTvServiceMoneyNumber;
    @Bind(R.id.rl_pay_mode)
    RelativeLayout mRlPayMode;
    @Bind(R.id.tv_service_money_submit)
    TextView mTvServiceMoneySubmit;
    @Bind(R.id.iv_service_money_bg)
    ImageView mIvServiceMoneyBg;

    @Bind(R.id.ll_service_money_close)
    LinearLayout mLlServiceMoneyClose;
    @Bind(R.id.tv_dialog_pay_model)
    TextView mTvDialogPayModel;
    private ServiceMoney money;
    private String models=UIHelper.BALANCE;
    private String busId;
    private IWXAPI api;
    private static final int SDK_PAY_FLAG = 1;

    public static OrderDetailsAddMoneyDialog newInstance(ServiceMoney serviceMoney, String busId) {
        OrderDetailsAddMoneyDialog fragment = new OrderDetailsAddMoneyDialog();
        Bundle bundle = new Bundle();
        bundle.putSerializable(SERVICEMONEY, serviceMoney);
        bundle.putString(BUS_ID, busId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (EmptyUtils.isEmpty(getArguments())) {
            dismiss();
        }
        money = (ServiceMoney) getArguments().getSerializable(SERVICEMONEY);
        busId = getArguments().getString(BUS_ID);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.Dialog_Share);
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_order_details_add_service_money, null);
        builder.setView(view);
        ButterKnife.bind(this, view);
        api = WXAPIFactory.createWXAPI(getActivity().getApplicationContext(), ClientConfig.WX_APP_ID);
        api.registerApp(ClientConfig.WX_APP_ID);
        init();
        return builder.create();
    }

    @Override
    public void onStart() {
        super.onStart();

        // 设置宽度为屏宽、靠近屏幕底部。
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(wlp);
    }

    public void init() {
        mEtServiceMoneyNumber.setText(money.getMinServiceMoney() + "");
        mTvServiceMoneyNumber.setText("￥" + money.getMinServiceMoney());
        mEtServiceMoneyNumber.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence s, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Double etMoney = Double.valueOf(String.valueOf(s));
                if (etMoney < money.getMinServiceMoney()) {
                    mEtServiceMoneyNumber.setText(money.getMinServiceMoney() + "");
                    mTvServiceMoneyNumber.setText("￥" + money.getMinServiceMoney());
                } else if (etMoney > money.getMxServiceMoney()) {
                    mEtServiceMoneyNumber.setText(money.getMxServiceMoney() + "");
                    mTvServiceMoneyNumber.setText("￥" + money.getMxServiceMoney());
                } else {
                    mTvServiceMoneyNumber.setText("￥" + s);
                }


            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        unSubscribe();
    }

    @OnClick({R.id.iv_service_money_subtract, R.id.iv_service_money_add, R.id.rl_pay_mode, R.id.tv_service_money_submit, R.id.ll_service_money_close})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_service_money_subtract:
                Double subMoney = Double.valueOf(mEtServiceMoneyNumber.getText().toString());
                mEtServiceMoneyNumber.setText(subMoney - money.getServiceMoneyStep() + "");
                break;
            case R.id.iv_service_money_add:
                Double addMoney = Double.valueOf(mEtServiceMoneyNumber.getText().toString());
                mEtServiceMoneyNumber.setText(addMoney + money.getServiceMoneyStep() + "");
                break;
            case R.id.rl_pay_mode:
                UIHelper.showDialogPayMode(getActivity());
                break;
            case R.id.tv_service_money_submit:
                addServiceMoney(mEtServiceMoneyNumber.getText().toString());
                break;
            case R.id.ll_service_money_close:
                dismiss();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PayModelEvent model) {
        models = model.getModel();
        if (model.getModel().equals(UIHelper.BALANCE)) {
            mTvDialogPayModel.setText(getActivity().getResources().getString(R.string.generic_pay_balance));
        } else if (model.getModel().equals(UIHelper.WECHAT)) {
            mTvDialogPayModel.setText(getActivity().getResources().getString(R.string.generic_pay_wechat));

        } else if (model.getModel().equals(UIHelper.ALIPAY)) {
            mTvDialogPayModel.setText(getActivity().getResources().getString(R.string.generic_pay_alipay));

        }

    }

    private void addServiceMoney(String money) {
        addSubscribe(DataManager.getInstance().getUserApi()
                .addServiceMoney(models, busId, money, MDConstant.PLATFORM)
                .compose(RxHelper.<RechargeEntity>defaultHandleResult())
                .subscribe(new RxSubscribe<RechargeEntity>() {
                    @Override
                    protected void onSucc(RechargeEntity rechargeEntity) {
                        pay(rechargeEntity);
                    }

                    @Override
                    protected void onFail(String msg) {

                    }
                }));
    }

    private void pay(final RechargeEntity payEntity) {
        Logger.e("完整的符合支付宝参数规范的订单信息：" + payEntity.getSign());
        if (models.equals(BALANCE)) {
            dismiss();
            EventBus.getDefault().post(new AddServiceEvent("0"));
        } else if (models.equals(WECHAT)) {
            PayReq req = new PayReq();
            req.appId = payEntity.getAppid();
            req.partnerId = payEntity.getPartnerid();
            req.prepayId = payEntity.getPrepayid();
            req.nonceStr = payEntity.getNoncestr();
            req.timeStamp = String.valueOf(payEntity.getTimestamp());
            req.packageValue = payEntity.getPackageX();
            req.sign = payEntity.getSign();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.sendReq(req);
        } else if (models.equals(ALIPAY)) {
            final String orderinfo = payEntity.getSign();
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    // 构造PayTask 对象
                    PayTask alipay = new PayTask(getActivity());
                    // 调用支付接口，获取支付结果
                    String result = alipay.pay(orderinfo, true);
                    Logger.e(" 支付接口：" + result);

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Logger.e("支付宝返回结果：" + resultInfo + "   " + resultStatus);
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(new AddServiceEvent("0"));
                        dismiss();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(getActivity(), "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PayEvent event) {
        if (event.getSucc().equals("0")) {
            EventBus.getDefault().post(new AddServiceEvent("0"));
        }
    }

    // rx总线
    private static CompositeSubscription compositeSubscription;

    public static void addSubscribe(Subscription subscription) {
        if (compositeSubscription == null) {
            compositeSubscription = new CompositeSubscription();
        }
        compositeSubscription.add(subscription);
    }

    public void unSubscribe() {
        if (compositeSubscription != null) {
            compositeSubscription.unsubscribe();
            compositeSubscription = null;
        }
    }
}
